<?php
declare (strict_types = 1);
namespace app\api\controller\union;

use app\LoginController;
use app\model\MyException;
use app\model\table\config\ConfigGlobal;
use app\model\table\union\Union;
use app\model\table\union\UnionHelp;
use app\model\table\user\User;
use app\model\tablenot\tool\Tool;
use think\facade\Db;
use hg\apidoc\annotation as Apidoc;


/**
 * @Apidoc\Title("工会-帮助")
 */
class UnionHelpController extends LoginController
{
    /**
     * @Apidoc\Title("工会-帮助-分页")
     * @Apidoc\Method("GET")
     * @Apidoc\Param ("page",require=true, type="int", desc="第几页")
     * @Apidoc\Param ("pagesize",require=true, type="int", desc="一页多少条")
     * @Apidoc\Returned("user_id", type="int", desc="用户id")
     * @Apidoc\Returned("UserInfo.name", type="int", desc="需要帮助的用户昵称")
     * @Apidoc\Returned("canHelp", type="int", desc="是否能够帮助【0:否；1:是】")
     * @Apidoc\Returned("max", type="int", desc="帮助最大数")
     * @Apidoc\Returned("now", type="int", desc="帮助当前数")
     */
    public function pageAction()
    {
        try {
            Tool::checkParam(['page','pagesize'], $this->get);
            $userId = $this->user['id'];
            $unionId = $this->user['union_id'];
            // 用户必须加入工会
            if($unionId == 0){
                throw new MyException("请加入工会后再操作");
            }
            $where['pagesize'] = $this->get['pagesize'];
            $where['orderBy'] = "created_at desc";
            $where[] = ['union_id','=',$unionId];
            $where[] = ['del_time','>',$this->time];
            $UnionHelpObj = UnionHelp::instance()->page($where);
            $JoinWith=['UserInfo'];
            UnionHelp::instance()->dealJoinWith($UnionHelpObj['data'],$JoinWith);
            foreach ($UnionHelpObj['data'] as $key=>$val){
                $help_user_idArr = explode(",", $val['help_user_id_str']);
                $UnionHelpObj['data'][$key]['canHelp'] = in_array($userId, $help_user_idArr) ? 0 : 1;
            }
            $this->setData($UnionHelpObj);
            $this->sendJson();
        } catch (MyException $e) {
            echo $e->toJson();
        }
    }


    /**
     * @Apidoc\Title("工会-帮助-发布帮助")
     * @Apidoc\Desc ("1. 用户必须加入工会。2.冷却中不能发布")
     * @Apidoc\Method("POST")
     */
    public function addAction()
    {
        try {
            $userId = $this->user['id'];
            $unionId = $this->user['union_id'];
            // 用户必须加入工会
            if($unionId == 0){
                throw new MyException("请加入工会后再操作");
            }
            // 每个帮助可以帮助最大次数
            $user_help_max = ConfigGlobal::instance()->findValue("user_help_max");

            // 用户帮助间隔时间(秒)
            $user_help_gap = ConfigGlobal::instance()->findValue("user_help_gap");

            // 获取用户最后一次发布的数据
            $where[] = ['user_id','=',$userId];
            $where[] = ['union_id','=',$unionId];
            $UnionHelpObj = UnionHelp::instance()->findOne($where, true);
            if(!empty($UnionHelpObj)){
                if(time() - strtotime($UnionHelpObj['created_at']) < $user_help_gap){
                    throw new MyException("冷却中");
                }
            }

            // 启动事务
            Db::startTrans();
            // 删除这个人之前所有的帮助
            UnionHelp::instance()->delMore(['user_id' => $userId]);

            // 插入数据
            $postData = array(
                'user_id' => $userId,
                'union_id' => $unionId,
                'max' => $user_help_max,
                'now' => 0,
                'help_user_id_str' => $userId,
                'del_time' => date("Y-m-d H:i:s", time()+$user_help_gap),
                'created_at' => $this->time,
            );
            UnionHelp::instance()->addOne($postData);
            Db::commit();
            $this->sendJson();
        } catch (MyException $e) {
            echo $e->toJson();
        }
    }

    /**
     * @Apidoc\Title("工会-帮助-帮助其他成员")
     * @Apidoc\Desc("1. 帮助和被帮助的人不在同一个工会不能帮助 2. 帮助已经满了不能再帮助， 3. 帮助过一次不能再帮助  4. 帮助成功后后台只给自己加一金币，体力由前段自己修改")
     * @Apidoc\Method("POST")
     * @Apidoc\Param ("id",require=true, type="int", desc="工会帮助列表id")
     */
    public function helpAction()
    {
        try {
            Tool::checkParam(['id'], $this->post);
            $id = $this->post['id'];
            $userId = $this->user['id'];
            $unionId = $this->user['union_id'];
            $UnionHelpObj = UnionHelp::instance()->findOne(['id'=>$id], true);
            if(empty($UnionHelpObj)){
                throw new MyException("数据不存在");
            }
            if($userId == $UnionHelpObj['user_id']){
                throw new MyException("自己不能帮助自己");
            }
            if($unionId != $UnionHelpObj['union_id']){
                throw new MyException("不在同一工会,不能帮助");
            }
            if($UnionHelpObj['max'] == $UnionHelpObj['now']){
                throw new MyException("帮助已达上限");
            }
            $help_user_idArr = explode(",", $UnionHelpObj['help_user_id_str']);
            if(in_array($userId, $help_user_idArr)){
                throw new MyException("已经帮助过了,不能再次帮助");
            }
            $help_user_idArr[] = $userId;
            $help_user_idArr = array_unique($help_user_idArr);

            // 启动事务
            Db::startTrans();
            $UnionHelpPostData = array(
                'id' => $id,
                'now' => $UnionHelpObj['now'] + 1,
                'help_user_id_str' => implode(",", $help_user_idArr)
            );
            UnionHelp::instance()->updateOne($UnionHelpPostData);
            // 给自己加金币
            $UserPostData = array(
                'id' => $userId,
                'gold' => $this->user['gold'] + 1,
                'help_num' => $this->user['help_num'] + 1,
            );
            User::instance()->updateOne($UserPostData);
            // 工会帮助总次数
            $UnionPostData = array(
                'id' => $unionId,
                'help_num' => $this->user['help_num'] + 1,
            );
            Union::instance()->updateOne($UnionPostData);
            Db::commit();
            $this->sendJson();
        } catch (MyException $e) {
            echo $e->toJson();
        }
    }
}
